package leetcode.primary;

import utils.linkedList.LinkedList;
import utils.linkedList.ListNode;

public class T92 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
//        int low = left-1,high = right+1;
        ListNode node = head;
        int i = 1;
        while(i!=left-1 && left!=1){
            i++;
            node=node.next;
        }
        ListNode low ;
        ListNode leftNode ;
        ListNode pre ;
        ListNode post ;
        if (left==1){
            low = null;
            leftNode = node;
        }else {
            low = node;
            leftNode = node.next;
            i++;
        }
        pre = low;
        post = leftNode.next;
        node = leftNode;

        while (i<right){
            node.next = pre;
            pre = node;
            node = post;
            post = node.next;
            i++;
        }

        node.next = pre;
        ListNode rightNode = node;
        ListNode high = post;

        if (low!=null){
            low.next = rightNode;
        }else {
            head = rightNode;
        }

        leftNode.next=high;
//        System.out.println("low="+low.val+",left.val="+leftNode.val+",right.val="+rightNode.val+",high="+high.val);
        return head;
    }

    public static void main(String[] args) {
        T92 t92 = new T92();
        LinkedList linkedList = new LinkedList();
        ListNode head = linkedList.initLinkedList(new int[]{5});
        ListNode node = t92.reverseBetween(head, 1, 1);
        while (node!=null){
            System.out.print(node.val+" ");
            node = node.next;
        }
    }
}
